package com.neusoft.dao.impl;

import com.neusoft.dao.UserDao;
import com.neusoft.pojo.User;
import com.neusoft.util.DBUtils;

import java.sql.*;

public class UserDaoImpl implements UserDao {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    @Override
    public User login(String uname, String pwd) {
        User user = null;
        try {
            //获得连接数据库对象
            conn = DBUtils.getConn();
            //预编译sql语句
            pstmt = conn.prepareStatement("select username,password from t_user where username=? and password=?");
            //处理占位符
            pstmt.setString(1,uname);
            pstmt.setString(2,pwd);
            //执行sql语句
            rs = pstmt.executeQuery();
            //处理结果集
            if(rs.next()){
                user = new User(rs.getString("username"),rs.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closeAll(rs,pstmt,conn);
        }
        return user;
    }

    @Override
    public int addUser(User user) {
        int result = 0;
        try {
            conn = DBUtils.getConn();
            pstmt = conn.prepareStatement("insert into t_user values (null,?,?)");
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getPassword());
            result = pstmt.executeUpdate();
            if(result>0){
                System.out.println("添加成功");
            }else{
                System.out.println("添加失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closeAll(null,pstmt,conn);
        }
        return result;
    }

    @Override
    public int delUser(int id) {
        return 0;
    }

    @Override
    public int modifyUser(User user) {
        return 0;
    }
}
